"""
@Project ：HD_project 
@File    ：jadp_api_01.py
@IDE     ：PyCharm
@Author  ：靓仔
@Date    ：2023/12/12 0012 11:26
"""
import sys
import requests
import json
from urllib.parse import urljoin
from utils.password_ascii import convert_to_custom_format
from utils.timeing import timing_decorator


class JapdApi:
    BASE_URL = "http://10.6.10.110/api/jadp/"

    def __init__(self):
        self.session = requests.Session()
        self.headers = {
            'Host': '10.6.10.110',
            'Origin': 'http://10.6.10.110',
            'Ratio': '960*1707',
            'Referer': 'http://10.6.10.110/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81'
        }
        self.token = self.session_login()
        self.user_info = self.get_company_per()
        self.system_management_params = self.extract_system_management_params()
        self.user_data = self.user_info_name()

    def session_login(self):
        url = urljoin(self.BASE_URL, "auth/session")
        data = {"account": "SuperAdmin", "password": convert_to_custom_format("hello")}
        res = self.session.post(url=url, json=data, headers=self.headers).text
        return res

    @timing_decorator
    def get_company_per(self):
        url = urljoin(self.BASE_URL, "personnel/users/search")
        params = {
            'pageNo': 1,
            'pageSize': 200000,
            'orgId': 20000001,
            'state': 1,
            'userState': 1,
            'fastQueryValue': '',
            'associateType': 1,
            '_': 1702261242508
        }
        res = json.loads(self.session.get(url=url, params=params, headers=self.headers).text)
        return res

    def user_info_name(self):
        return [
            {
                "id": user_name["userId"],
                'name': user_name["employeeName"],
                'account': user_name["account"],
                'name_full_path': user_name["nameFullPath"]
            }
            for user_name in self.user_info["list"]
        ]

    # 根据组织名称获取id
    def get_name_by_path(self, search_value):
        matching_names = [
            item.get('id') for item in self.user_data
            if item.get('name_full_path') and search_value in item['name_full_path']
        ]
        return matching_names

    def get_name_to_id(self, search_value):
        matching_names = []

        # Ensure search_value is a non-empty string
        if not search_value or not isinstance(search_value, str):
            return matching_names

        # Use case-insensitive matching for account names
        search_value_lower = search_value.lower()

        for item in self.user_data:
            if 'account' in item and isinstance(item['account'], str):
                if search_value_lower == item['account'].lower():
                    matching_names.append(item.get('id'))

        return matching_names

    def get_name(self, search_value):
        matching_names = [
            item.get('name') for item in self.user_data
            if item.get('name_full_path') and item['name_full_path'].endswith(search_value)
        ]
        return matching_names

    def get_name_(self, search_value):
        matching_names = [
            item.get('name') for item in self.user_data
            if item.get('name') and item['name'].endswith(search_value)
        ]
        return matching_names

    def get_id_by_path(self, search_value):
        for role_info in self.system_management_params["role_info_list"]:
            if role_info['roleName'] == search_value:
                return role_info['roleId']
        return None

    # noinspection PyShadowingNames,DuplicatedCode
    def extract_system_management_params(self):
        url = urljoin(self.BASE_URL, "permission/roles/search")
        data = {
            'pageNo': 1,
            'pageSize': 2000,
            'roleClassifyId': 'AF7F3C52C77B409AABBFF2EB38D3DEA5',
            'fastQueryValue': '',
            'cascadeQuery': 0,
            '_': 1702278165589
        }
        res = json.loads(self.session.get(url=url, params=data, headers=self.headers).text)
        role_info_list = [
            {
                "roleId": info_list.get("roleId"),
                "roleName": info_list.get("roleName"),
            }
            for info_list in res.get("list")
        ]
        role_name_list = [info_list["roleName"] for info_list in res.get("list")]
        return {"role_info_list": role_info_list, "role_name_list": role_name_list}

    def extract_system_management_params_name(self):
        return self.system_management_params["role_name_list"]

    # noinspection PyShadowingNames
    def per_import(self, role_name, depa_name):
        """
        :type depa_name: object
        :type role_name: object
        """
        department_id = self.get_id_by_path(role_name)
        name = ', '.join(map(str, self.get_name_(depa_name)))
        # user_id = self.get_name_by_path(depa_name)
        user_id = self.get_name_to_id(depa_name)
        url = urljoin(self.BASE_URL, f"permission/subjectRole?roleId={department_id}")
        res = self.session.post(url=url, json=user_id, headers=self.headers).status_code
        if res == 200:
            return f"【{depa_name}】的人员：【{user_id}】添加到【{role_name}】权限成功!"

    def dept_per_import(self, role_name, depa_name):
        """
        :type depa_name: object
        :type role_name: object
        """
        department_id = self.get_id_by_path(role_name)
        name = ', '.join(map(str, self.get_name(depa_name)))
        user_id = self.get_name_by_path(depa_name)
        url = urljoin(self.BASE_URL, f"permission/subjectRole?roleId={department_id}")
        res = self.session.post(url=url, json=user_id, headers=self.headers).status_code
        if res == 200:
            return f"【{depa_name}】的人员：【{name}】添加到【{role_name}】权限成功!"


if __name__ == "__main__":
    japd_instance = JapdApi()
    role_name_list = japd_instance.extract_system_management_params_name()
    for role_name in role_name_list:
        # print(japd_instance.per_import(role_name, "cuijin"))
        print(japd_instance.dept_per_import(role_name, "哈尔滨电气集团有限公司/哈电集团（本部）/创新与数字化部"))
    # print(japd_instance.per_import("我的测试", "哈尔滨电气集团有限公司/哈尔滨电气股份有限公司/电机公司/国际经营部"))
